package controllers

import (
	"HomeMaterialManagementSystem/db"
	"HomeMaterialManagementSystem/models"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func BindRouters(r *gin.Engine) {
	r.Any("/login", Login)

	r.Use(AuthRequired())
	{
		r.Any("/logout", Logout)
		r.Any("/item", itemHandler)
		r.Any("/settings", settingsHandler)
		r.GET("/items", itemsHandler)
		r.GET("/dashboard", dashboardIndex)

		// API
		r.POST("/api/barcode", apiBarcodeHandler)

	}
}

func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		sessionText, err := c.Cookie("hmmssession")
		if err != nil {
			c.Redirect(http.StatusFound, "/login")
			return
		}
		c.Set("sessionText", sessionText)
		session := models.Session{}
		r := db.GetORM().Where(&models.Session{SessionText: sessionText}).First(&session)
		if r.Error != nil {
			log.Printf("%+v\n", r.Error)
			c.Redirect(http.StatusFound, "/login")
			return
		}
		c.Set("user", session.User)
		c.Set("username", session.User.Name)

		c.Next()

		// 设置 example 变量
		// c.Set("example", "12345")

		// 请求前

		// c.Next()

		// 请求后
	}
}
